import React, { PureComponent } from 'react';
import { DownOutlined, PlusOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
Card, Col, Row, // Table,
Button, // Select,
Input, // Badge,
message, // Radio,
Dropdown, Menu, // pagination,
Modal, Divider
} from 'antd';
import moment from 'moment';
import { connect } from 'dva';
// eslint-disable-next-line import/no-extraneous-dependencies
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
// import { esAxios, outExcelFun } from '@/utils/utils';
import styles from '@/utils/utils.less';
import Customer from '../../components/Customer';
import DictCode from '../../components/DictCode';
import downloadFile from '@/utils/utils';

const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ insback, loading }) => ({
  loading: loading.models.insback,
  // tabList: insback.tabList,
  // activeKey: insback.activeKey,
  pageData: insback.pageData,
  formFieldsValue: insback.formFieldsValue,
  expandForm: insback.expandForm,
}))
@Form.create()
class InsBack extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      selectedRows: [],
      selectedRowKeys: [],
    };
    this.tableSearchLayout = {
      labelCol: {
        lg: {
          span: 7,
        },
        xl: {
          span: 6,
        },
        xxl: {
          span: 4,
        },
      },
      wrapperCol: {
        xxl: {
          span: 17,
        },
      },
    };
  }

  componentDidMount = () => {
    const {
      pageData: { pagination },
      location,
      // activeKey = '1',
    } = this.props;
    const { isMenuLink } = location.query;
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
    // this.getList(pagination.current, pagination.pageSize);
  };

  // // 查询
  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'insback/updateModelData',
        payload: { formFieldsValue: fieldsValue },
      });
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
      });
      const pagerArg = { currentPage, pageSize };
      const values = {
        ...formFieldsValue,
        pagerArg,
      };
      dispatch({
        type: 'insback/fetchList',
        payload: {
          ...values,
        },
      });
      this.setState({
        formValues: values,
      });
    });
  };

  downExcel = () => {
    const { pageData } = this.props;
    const { formValues, selectedRowKeys } = this.state;
    const {
      pagination: { total },
    } = pageData;
    Object.keys(formValues).forEach(key => {
      if (key === 'pagerArg') {
        delete formValues.pagerArg;
      }
    });

    if (Number(total) === 0) {
      message.warning('无查询结果，不可导出');
    } else {
      downloadFile(
        { ...formValues, proveSerHdlIds: selectedRowKeys },
        '/esApi/proveHdl/export',
        'POST'
      );
    }
    // });
  };

  // 导出
  outExcel = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length) {
      this.downExcel();
    } else {
      confirm({
        title: `如果不选择数据，则默认导出当前列表下所有数据`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.downExcel();
        },
      });
    }
  };

  // 删除
  canceldeal = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    // const { lines, nowPage, pageNum } = this.state;
    // const newlines = lines;
    const canceldealArr = [];
    const values = {};
    if (selectedRows.length) {
      // eslint-disable-next-line array-callback-return
      selectedRows.map(item => {
        const obj = {};
        obj.proveSerHdlId = item.proveSerHdlId;
        obj.vno = item.vno;
        canceldealArr.push(obj);
      });
      values.list = canceldealArr;
      confirm({
        title: '您确定要删除吗？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          dispatch({
            type: 'insback/deleteData',
            payload: {
              ...values,
            },
          });
        },
      });
    } else {
      message.warning('至少选择一条数据');
    }
  };

  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'insback/updateModelData',
      payload: { formFieldsValue: {} },
    });
  };

  toggleForm = () => {
    // const { expandForm } = this.state;
    const { expandForm, dispatch } = this.props;
    dispatch({
      type: 'insback/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    await this.resetSearch();
    await this.getList();
    const { dispatch } = this.props;
    dispatch({
      type: 'insback/updateModelData',
      payload: { expandForm: false },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;

    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入姓名" maxLength={15} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入证件号" maxLength={18} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证明类型" {...this.tableSearchLayout}>
              {getFieldDecorator('proveType', {
                initialValue: formFieldsValue.proveType,
              })(<DictCode dictType="PROVE_TYPE" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.tableSearchLayout}>
              {getFieldDecorator('custId', {
                initialValue: formFieldsValue.custId,
              })(<Customer attr />)}
            </FormItem>
          </Col>
          <Col>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                收起 <UpOutlined />
              </a>
            </div>
          </Col>
        </Row>

        {/* <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div> */}
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入姓名" maxLength={15} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入证件号" maxLength={18} />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { pageData, loading } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;
    const menu = (
      <Menu>
        <Menu.Item>
          <a onClick={this.outExcel}>导出</a>
        </Menu.Item>
        <Menu.Item>
          <a onClick={this.canceldeal}>删除</a>
        </Menu.Item>
      </Menu>
    );
    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '证件号',
        dataIndex: 'certNo',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },

      {
        title: '证明类型',
        dataIndex: 'proveTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '状态',
        dataIndex: 'stateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '办理人',
        dataIndex: 'hdlName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '操作时间',
        dataIndex: 'operTime',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            {Number(record.state) === 1 ? null : (
              <span>
                <a
                  onClick={() =>
                    router.push(`/hrmanage/issueproof/update?id=${record.proveSerHdlId}`)
                  }
                >
                  修改
                </a>
                <Divider type="vertical" />
              </span>
            )}

            <a
              onClick={() => router.push(`/hrmanage/issueproof/detail?id=${record.proveSerHdlId}`)}
            >
              查看
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tabCard}>
          <Row style={{ marginBottom: '20px' }}>
            <Col span={10} offset={0}>
              <Button
                type="primary"
                style={{ marginRight: '10px' }}
                onClick={() => router.push('/hrmanage/issueproof/add')}
              >
                <PlusOutlined style={{ fontSize: 14 }} />
                开证明
              </Button>
              <Dropdown overlay={menu}>
                <Button>更多</Button>
              </Dropdown>
            </Col>
          </Row>
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={pageData}
            columns={columns}
            selectedRowKeys={selectedRowKeys}
            rowKey="proveSerHdlId"
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default InsBack;
